package com.fyk.service;

import com.fyk.dao.UserDao;
import com.fyk.entity.User;
import com.fyk.utils.UuidUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;

@Service
@Transactional  //开启声明式事务
public class UserServiceImpl implements UserService{

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    private UserDao userDao;
    @Autowired
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public boolean queryUserByUserName(User user) {
        //再判断从数据库通过用户名拿取的用户是否存在
        User dbUser = userDao.queryUserByUserName(user.getUserName());
        if (ObjectUtils.isEmpty(dbUser)) throw new RuntimeException("该用户不存在");
        //再判断用户名密码是否正确,比较加密后的密码
        String realPwd = DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8));
        if (!realPwd.equals(dbUser.getPassword())) throw new RuntimeException("密码错误");
        return true;
    }

    @Override
    public void addUser(User user) {
        //对用户的明文密码做加密处理
        String newPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8));
        user.setPassword(newPassword);
        userDao.addUser(user);
    }
}
